package com.tbit.uqbike.service.business.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.UserAuthWhiteList;
import com.tbit.uqbike.object.pojo.dto.AuthWhiteListDownloadDTO;
import com.tbit.uqbike.object.pojo.dto.BatchRegisterAuthDTO;
import com.tbit.uqbike.object.pojo.dto.UserAuthWhiteListDTO;
import com.tbit.uqbike.object.pojo.vo.UserAuthWhiteListVO;
import com.tbit.common.entity.view.PageResult;
import com.tbit.uqbike.service.business.StudentAuthApplyService;
import com.tbit.uqbike.service.business.UserAuthWhiteListService;
import com.tbit.uqbike.webmanager.dao.core.UserAuthWhiteListDao;
import com.tbit.uqbike.webmanager.util.csv.CsvExportUtils;
import com.tbit.uqbike.webmanager.util.csv.entity.DownloadDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserAuthWhiteListServiceImpl implements UserAuthWhiteListService {

    @Autowired
    private UserAuthWhiteListDao userAuthWhiteListDao;

    @Autowired
    private StudentAuthApplyService studentAuthApplyService;
    @Autowired
    CsvExportUtils csvExportUtils;

    @Override
    public PageResult queryPage(Integer brandId, String authNo, String name, Integer pageSize, Integer pageIndex, Date startTime, Date endTime) {

//        QueryWrapper<UserAuthWhiteList> wrapper = new QueryWrapper<>();
//        wrapper.lambda().eq(UserAuthWhiteList::getBrandId, brandId);
//        if(StringUtils.hasLength(authNo)){
//            wrapper.lambda().eq(UserAuthWhiteList::getAuthNo, authNo);
//        }
//        if(StringUtils.hasLength(name)){
//            wrapper.lambda().eq(UserAuthWhiteList::getName, name);
//        }

        Page<UserAuthWhiteListDTO> page = userAuthWhiteListDao.pageByCondition(new Page<>(pageIndex, pageSize), brandId, authNo, name, startTime, endTime);

        PageResult pageResult = new PageResult();
        pageResult.setList(page.getRecords());
        pageResult.setPage((int) page.getCurrent());
        pageResult.setTotalPages((int) page.getPages());
        pageResult.setSize((int) page.getSize());
        pageResult.setTotal(page.getTotal());
        return pageResult;
//        ALTER TABLE `uqbike-core`.`studentauthapply`
//        ADD INDEX `index_accountId_studentNO`(`accountId`, `studentNO`) USING BTREE;
    }

    @Override
    public void update(UserAuthWhiteListVO vo, Integer accountUserId) {
        UserAuthWhiteList userAuthWhiteList = new UserAuthWhiteList();
        BeanUtils.copyProperties(vo, userAuthWhiteList);
        userAuthWhiteList.setUpdateUserId(accountUserId);

//        Integer total = studentAuthApplyService.getTotal(vo.getBrandId(), 1, null, vo.getAuthNo());
//        userAuthWhiteList.setAuthQuantity(total);
        if(vo.getId() == null){
            List<UserAuthWhiteList> userAuthWhiteLists = userAuthWhiteListDao.selectList(new QueryWrapper<UserAuthWhiteList>().lambda()
                    .eq(UserAuthWhiteList::getAuthNo, vo.getAuthNo()).eq(UserAuthWhiteList::getBrandId, vo.getBrandId()));
            if(!CollectionUtils.isEmpty(userAuthWhiteLists)){
                throw new BaseException(SystemCodeEnum.AUTH_NO_IS_EXIST);
            }
            userAuthWhiteListDao.insert(userAuthWhiteList);
        }else{
            List<UserAuthWhiteList> userAuthWhiteLists = userAuthWhiteListDao.selectList(new QueryWrapper<UserAuthWhiteList>().lambda()
                    .eq(UserAuthWhiteList::getAuthNo, vo.getAuthNo()).eq(UserAuthWhiteList::getBrandId, vo.getBrandId())
                    .ne(UserAuthWhiteList::getId, vo.getId()));
            if(!CollectionUtils.isEmpty(userAuthWhiteLists)){
                throw new BaseException(SystemCodeEnum.AUTH_NO_IS_EXIST);
            }
            userAuthWhiteListDao.updateById(userAuthWhiteList);
        }
    }
    @Override
    public void del(Integer id){
        userAuthWhiteListDao.deleteById(id);
    }

    @Override
    public void batchUpdate(List<UserAuthWhiteList> list, Integer override) {
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        if(override == 0){
            List<String> conditionNos = list.stream().map(UserAuthWhiteList::getAuthNo).collect(Collectors.toList());
            List<UserAuthWhiteList> userAuthWhiteLists = userAuthWhiteListDao.selectList(new QueryWrapper<UserAuthWhiteList>().lambda()
                    .in(UserAuthWhiteList::getAuthNo, conditionNos)
                    .eq(UserAuthWhiteList::getBrandId, list.get(0).getBrandId()));

            Map<String, UserAuthWhiteList> existMap = userAuthWhiteLists.stream().collect(Collectors.toMap(UserAuthWhiteList::getAuthNo, o -> o));
            List<UserAuthWhiteList> removeList = new ArrayList<>();
            for (UserAuthWhiteList userAuthWhiteList : list) {
                if(existMap.containsKey(userAuthWhiteList.getAuthNo())){
                    removeList.add(userAuthWhiteList);
                }
            }
            list.removeAll(removeList);
        }
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        userAuthWhiteListDao.insertOrUpdateByBatch(list);
    }

    @Override
    public String download(Integer brandId, String authNo, String name, Date startTime, Date endTime, DownloadDTO downloadDTO) {
        File tempFile = csvExportUtils.getTempFile();
        try{
            QueryWrapper<UserAuthWhiteList> wrapper = new QueryWrapper<>();
            wrapper.lambda().eq(UserAuthWhiteList::getBrandId, brandId);
            if(StringUtils.hasLength(authNo)){
                wrapper.lambda().eq(UserAuthWhiteList::getAuthNo, authNo);
            }
            if(StringUtils.hasLength(name)){
                wrapper.lambda().eq(UserAuthWhiteList::getName, name);
            }
            List<AuthWhiteListDownloadDTO> list = userAuthWhiteListDao.listByCondition(brandId, authNo, name, startTime, endTime);
            File file = csvExportUtils.exportCsv(AuthWhiteListDownloadDTO.class, tempFile, downloadDTO.getFileName(), list);
            String uploadFileName = UUID.randomUUID().toString().replaceAll("-", "");
            return csvExportUtils.uploadZip(tempFile, uploadFileName, file);
        }finally {
            FileUtil.del(tempFile);
        }

    }

    @Override
    public List<String> importCheck(List<UserAuthWhiteList> list) {
        if(CollectionUtils.isEmpty(list)){
            throw new BaseException(SystemCodeEnum.AUTH_NO_MUST_NOT_NULL);
        }
        List<String> conditionNos = list.stream().map(UserAuthWhiteList::getAuthNo).collect(Collectors.toList());
        List<UserAuthWhiteList> userAuthWhiteLists = userAuthWhiteListDao.selectList(new QueryWrapper<UserAuthWhiteList>().lambda()
                .in(UserAuthWhiteList::getAuthNo, conditionNos)
                .eq(UserAuthWhiteList::getBrandId, list.get(0).getBrandId()));

        List<String> existNos = new ArrayList<>();
        if(!CollectionUtils.isEmpty(userAuthWhiteLists)){
            existNos = userAuthWhiteLists.stream().map(UserAuthWhiteList::getAuthNo).collect(Collectors.toList());
        }
        return existNos;
    }
}
